package com.xiegang.apipassenger.Service;

import com.xiegang.internalcommon.constant.CommonStatusEnum;
import com.xiegang.internalcommon.constant.TokenConstans;
import com.xiegang.internalcommon.dto.ResponseResult;
import com.xiegang.internalcommon.dto.TokenResult;
import com.xiegang.internalcommon.response.TokenResponse;
import com.xiegang.internalcommon.util.JWTUtil;
import com.xiegang.internalcommon.util.RedisPrefixUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.xml.ws.Response;
import java.util.concurrent.TimeUnit;

/**
 * @author xieGang
 * @description
 * @date 2023/3/5 19:40
 **/
@Service
public class TokenService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    public ResponseResult refreshToken(@RequestParam("refreshToken") String refreshTokenSrc) {
        TokenResult tokenResult = JWTUtil.parseToken(refreshTokenSrc);

        if (tokenResult == null) {
            return ResponseResult.fail(CommonStatusEnum.TOKENERROR.getCode(), CommonStatusEnum.TOKENERROR.getMessage());
        }
        String phone = tokenResult.getPhone();
        String identity = tokenResult.getIdentity();
        String refreshTokenKey = RedisPrefixUtils.generateTokenKey(phone, identity, TokenConstans.REFRESH_TOKEN_TYPE);
        String refreshTokenRedis = stringRedisTemplate.opsForValue().get(refreshTokenKey);

        if (StringUtils.isBlank(refreshTokenRedis) || !refreshTokenSrc.trim().equals(refreshTokenRedis.trim())) {
            return ResponseResult.fail(CommonStatusEnum.TOKENERROR.getCode(), CommonStatusEnum.TOKENERROR.getMessage());
        }

        String accessTokenKey = RedisPrefixUtils.generateTokenKey(phone, identity, TokenConstans.ACCESS_TOKEN_TYPE);
        String accessToken = JWTUtil.generatorToken(phone, identity, TokenConstans.ACCESS_TOKEN_TYPE);

        String refreshToken = JWTUtil.generatorToken(phone, identity, TokenConstans.REFRESH_TOKEN_TYPE);

        stringRedisTemplate.opsForValue().set(accessTokenKey,accessToken,30, TimeUnit.DAYS);
        stringRedisTemplate.opsForValue().set(refreshTokenKey,refreshToken,31, TimeUnit.DAYS);

        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setRefreshToken(refreshToken);
        tokenResponse.setAccessToken(accessToken);

        return ResponseResult.success(tokenResponse);
    }


}
